/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved.
 *
 */
import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { runHvigorAsync } from '../../common/common';
import { commonJson5Operation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: [ModuleTemplateType.SharedLibrary, ModuleTemplateType.FeatureEmptyAbility],
};

// eslint-disable-next-line max-lines-per-function
const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();

  const feature = project.getModule('feature');
  const featureRootPath = feature.moduleRootPath();

  const module = project.getModule('shareLibrary');
  const moduleRootPath = module.moduleRootPath();
  const commands = '--mode module -p product=default -p module=shareLibrary@default assembleHsp --analyze=normal --parallel --incremental --daemon'.split(' ');
  const artifactRoot = path.resolve(moduleRootPath, 'build/default/intermediates/hsp_metadata/default/output_metadata.json');

  const result1 = await runHvigorAsync(projectRootPath, commands);
  record.addStep('首次构建，GenerateMetadata为Finished', result1);
  expect(result1.stdout).toContain('BUILD SUCCESSFUL');
  expect(result1.stdout).toContain('Finished :shareLibrary:default@GenerateMetadata');
  expect(fse.existsSync(artifactRoot)).toEqual(true);

  const result2 = await runHvigorAsync(projectRootPath, commands);
  record.addStep('不做任何更改，再次构建，GenerateMetadata为UP-TO-DATE', result2);
  expect(result2.stdout).toContain('BUILD SUCCESSFUL');
  expect(result2.stdout).toContain('UP-TO-DATE :shareLibrary:default@GenerateMetadata');
  expect(fse.existsSync(artifactRoot)).toEqual(true);

  // 修改outputFiles
  fse.removeSync(artifactRoot);
  const result3 = await runHvigorAsync(projectRootPath, commands);
  record.addStep('删除产物，再次构建，GenerateMetadata为Finished', result3);
  expect(result3.stdout).toContain('BUILD SUCCESSFUL');
  expect(result3.stdout).toContain('Finished :shareLibrary:default@GenerateMetadata');
  expect(fse.existsSync(artifactRoot)).toEqual(true);

  // 修改moduleDeviceType | buildOption
  await commonJson5Operation(path.resolve(moduleRootPath, 'build-profile.json5'), (json) => {
    json.targets[0].config = { deviceType: ['2in1'] };
    return json;
  });

  const result5 = await runHvigorAsync(projectRootPath, commands);
  record.addStep('修改moduleDeviceType，再次构建，GenerateMetadata为Finished', result5);
  expect(result5.stdout).toContain('BUILD SUCCESSFUL');
  expect(result5.stdout).toContain('Finished :shareLibrary:default@GenerateMetadata');
  expect(fse.existsSync(artifactRoot)).toEqual(true);

  // 2、配签名 | 修改工程级 build-profile.json5
  const commonSignPath = path.resolve('test/resources/common/sign/myapplication_debug');
  const OHOS_SIGNATURE_TEMPLATE = {
    name: 'default',
    type: 'HarmonyOS',
    material: {
      certpath: `${commonSignPath}.cer`,
      storePassword: '0000001B734C857D79A0AFE684D4F7C9461064D24605328C9AC15302BCB7D9606F8B6D82949497240F684F',
      keyAlias: 'debugKey',
      keyPassword: '0000001B92B7D7143F022695515F8F862090F22016F59D86A642F36AA953ECD76A5DAE6941C04D8FFFF864',
      profile: `${commonSignPath}.p7b`,
      signAlg: 'SHA256withECDSA',
      storeFile: `${commonSignPath}.p12`,
    },
  };
  await commonJson5Operation(path.resolve(projectRootPath, 'build-profile.json5'), async (json5) => {
    json5.app.signingConfigs = [OHOS_SIGNATURE_TEMPLATE];
  });

  const result6 = await runHvigorAsync(projectRootPath, commands);
  record.addStep('修改product，再次构建，GenerateMetadata为Finished', result6);
  expect(result6.stdout).toContain('BUILD SUCCESSFUL');
  expect(result6.stdout).toContain('Finished :shareLibrary:default@GenerateMetadata');
  expect(fse.existsSync(artifactRoot)).toEqual(true);

  // 修改inputFiles config.json
  await commonJson5Operation(path.resolve(moduleRootPath, 'src/main/module.json5'), (json) => {
    json.module.installationFree = !json.module.installationFree;
    return json;
  });
  const result8 = await runHvigorAsync(projectRootPath, commands);
  record.addStep('修改config.json文件，再次构建，GenerateMetadata为Finished', result8);
  expect(result8.stdout).toContain('BUILD SUCCESSFUL');
  expect(result8.stdout).toContain('Finished :shareLibrary:default@GenerateMetadata');
  expect(fse.existsSync(artifactRoot)).toEqual(true);

  const featureCommands = '--mode module -p product=default -p module=feature@default assembleHap --analyze=normal --parallel --incremental --daemon'.split(
    ' ',
  );

  const result9 = await runHvigorAsync(projectRootPath, featureCommands);
  record.addStep('首次构建，GenerateMetadata为Finished', result9);
  expect(result9.stdout).toContain('BUILD SUCCESSFUL');
  expect(result9.stdout).toContain('Finished :feature:default@GenerateMetadata');
  expect(fse.existsSync(artifactRoot)).toEqual(true);

  const result10 = await runHvigorAsync(projectRootPath, featureCommands);
  record.addStep('不做任何更改，再次构建，GenerateMetadata为UP-TO-DATE', result10);
  expect(result10.stdout).toContain('BUILD SUCCESSFUL');
  expect(result10.stdout).toContain('UP-TO-DATE :feature:default@GenerateMetadata');
  expect(fse.existsSync(artifactRoot)).toEqual(true);

  // 修改entryModules
  await commonJson5Operation(path.resolve(featureRootPath, 'build-profile.json5'), (json) => {
    json.entryModules = ['entry'];
    return json;
  });

  const result11 = await runHvigorAsync(projectRootPath, featureCommands);
  record.addStep('修改entryModules，再次构建，GenerateMetadata为Finished', result11);
  expect(result11.stdout).toContain('BUILD SUCCESSFUL');
  expect(result11.stdout).toContain('Finished :feature:default@GenerateMetadata');
  expect(fse.existsSync(artifactRoot)).toEqual(true);

  // 修改远程HSP  修改无效
  // await commonJson5Operation(path.resolve(projectRootPath, 'oh-package.json5'), json => {
  //   json.devDependencies.hsp = '1.0.0';
  //   return json;
  // });
  //
  // const result14 = await runHvigorAsync(projectRootPath, entryCommands);
  // record.addStep('修改远程HSP，再次构建，GenerateMetadata为Finished', result14);
  // expect(result14.stdout).toContain('BUILD SUCCESSFUL');
  // expect(result14.stdout).toContain('Finished :entry:default@GenerateMetadata');
  // expect(fse.existsSync(artifactRoot)).toEqual(true);
};

TestCaseBuilder.builder()
  .caseName('GenerateMetadata')
  .description('GenerateMetadata任务增量测试用例')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).build())
  .testFun(testfun)
  .load();
